<?php
import('ORG.Util.Function');
import('@.Org.BaseTool');
import('@.Org.GoodsTool');

class GoodsAction extends CommonAction {
	
	public function _initialize(){
		parent::_initialize();
		$this->assign('li_selected',	'goods');
		$this->assign("global_title",	"在线商城_wifi智能云音箱，wifi音箱，wifi音乐盒，无线耳机，wifi U盘_音伴尔官网");	
	}
	
	public function index(){		
		/*针对单个产品进行推荐*/
		/*wifi音乐盒子*/
		$recommend_first_goods	=	M('Goods')->field("goods_id,goods_sn,goods_name,market_price,shop_price,promote_price,goods_img,goods_thumb,is_best,is_new,is_hot")->where("goods_sn='YBR_000034'")->find();
		/*wifiU盘*/
		$recommend_second_goods	=	M('Goods')->field("goods_id,goods_sn,goods_name,market_price,shop_price,promote_price,goods_img,goods_thumb,is_best,is_new,is_hot")->where("goods_sn='YBR_000039'")->find();
		/*蓝牙无线头戴式耳机*/
		$recommend_three_goods	=	M('Goods')->field("goods_id,goods_sn,goods_name,market_price,shop_price,promote_price,goods_img,goods_thumb,is_best,is_new,is_hot")->where("goods_sn='YBR_000000'")->find();
		/*wifi插座*/
		$recommend_forth_goods	=	M('Goods')->field("goods_id,goods_sn,goods_name,market_price,shop_price,promote_price,goods_img,goods_thumb,is_best,is_new,is_hot")->where("goods_sn='YBR_000035'")->find();
		
		//菜单下拉商品列表
        $recommend_goods_list	=	M('Goods')->limit(4)->field("goods_id,goods_sn,goods_name,market_price,shop_price,promote_price,goods_img,goods_thumb,is_best,is_new,is_hot")->order("goods_id asc")->where("is_best= 1")->select();
		//先默认销售数据
		foreach ($recommend_goods_list as $k=>$v){				
			if($v['goods_id'] == 34){
				$recommend_goods_list[$k]['sell_amount'] = 132;
			}
			else if($v['goods_id'] == 35){
				$recommend_goods_list[$k]['sell_amount'] = 98;
			}
			else if($v['goods_id'] == 37){
				$recommend_goods_list[$k]['sell_amount'] = 121;
			}
			else if($v['goods_id'] == 39){
				$recommend_goods_list[$k]['sell_amount'] = 209;
			}
		}
				
		$this->assign("first_goods",			$recommend_first_goods);
		$this->assign("second_goods",			$recommend_second_goods);
		$this->assign("three_goods",			$recommend_three_goods);
		$this->assign("forth_goods",			$recommend_forth_goods);
		$this->assign("recommend_goods_list",	$recommend_goods_list);
		$this->display();
	}
	
    /**
     * 商品详情
     * 
     */
   	public function item(){		
   		$CommonModel		=	new CommonModel();    	
    	$goods_id			=	$_GET['id'];
    	
    	$this->assign('helps',        	get_shop_help()); // 网店帮助
    	$this->assign('goods_id',      	$goods_id); // 网店帮助
    	
	    $this->assign('image_width',  	$GLOBALS['_CFG']['image_width']);
	    $this->assign('image_height', 	$GLOBALS['_CFG']['image_height']);
	    /*购物车*/
	    $this->assign('my_cart', 		insert_cart_info());
	    
	    $this->assign('id',           	$goods_id);
	    $this->assign('type',         	0);
	    $this->assign('cfg',          	$GLOBALS['_CFG']);
	        
	    /* 获得商品的信息 */
	    $goods 				= 	get_goods_info($goods_id);   
		
		//标签title
		$this->assign("global_title",		$goods['goods_name'] . "_音伴尔官网");	
				
	    if ($goods === false){
	       $this->error("不存在该商品");
	    }
	    else{
	    	/*商品品牌连接*/
	        if ($goods['brand_id'] > 0){
	            //$goods['goods_brand_url'] 	= 	build_uri('brand', array('bid'=>$goods['brand_id']), $goods['goods_brand']);
	        }			
	        $shop_price   						= 	$goods['shop_price'];	        
	        /*促销活动信息*/
		    $this->assign('promotion',      get_promotion_info($goods_id));
		    $this->assign('promotion_info', get_promotion_info());	        
	        //关联商品	        
	        $linked_goods					= 	get_linked_goods($goods_id);	        	        
	        //$this->assign('attribute_linked',    get_same_attribute_goods($properties));         	 // 相同属性的关联商品
	        //$this->assign('related_goods',       $linked_goods);                                   // 关联商品
	        //$this->assign('goods_article_list',  get_linked_articles($goods_id));                  // 关联文章	        
	        //$this->assign('bought_goods',        get_also_bought($goods_id));                      // 购买了该商品的用户还购买了哪些商品
	        //$this->assign('goods_rank',          get_goods_rank($goods_id));                       // 商品的销售排名
	        /*//获取tag
	        $tag_array 	= 	get_tags($goods_id);
	        $this->assign('tags',                $tag_array);                                    // 商品的标记*/
	        /*//商品分类
	        $catlist 						= 	array();
	        foreach(get_parent_cats($goods['cat_id']) as $k=>$v){
	            $catlist[] 			= $v['cat_id'];
	        }
	        $this->assign('categories',         get_categories_tree($goods['cat_id']));  // 分类树*/
	
	        //可以再购买以后，使用红包兑换,购买该商品可以得到多少钱的红包
	        if ($goods['bonus_type_id'] > 0){
	            $time 		= 	gmtime();
	            $sql 		= 	"SELECT type_money FROM " .'ybr_bonus_type' .
			                    " WHERE type_id = '$goods[bonus_type_id]' " .
			                    " AND send_type = '" . SEND_BY_GOODS . "' " .
			                    " AND send_start_date <= '$time'" .
			                    " AND send_end_date >= '$time'";
	            $goods['bonus_money'] 		= 	floatval( $CommonModel->getOne($sql) );
	            if ($goods['bonus_money'] > 0){
	                $goods['bonus_money'] 	= 	price_format($goods['bonus_money']);
	            }
	        }
	        
	        /*获取关联礼包*/
	        $package_goods_list 			= 	get_package_goods_list($goods['goods_id']);
	        $this->assign('package_goods_list',	$package_goods_list);
	        $this->assign('keywords',           htmlspecialchars($goods['keywords']));
	        $this->assign('description',        htmlspecialchars($goods['goods_brief']));	        
			$this->assign('promote_end_time',   $goods['gmt_end_time']); // 促销结束日期
	        /*//购买商品达到以下数量区间时可享受的优惠价格：*/
	        $volume_price_list 				= 	get_volume_price_list($goods['goods_id'], '1');
	        $this->assign('volume_price_list',$volume_price_list);    // 商品优惠价格区间*/
	        /*商品属性*/
	        $properties 					= 	get_goods_properties($goods_id);  // 获得商品的规格和属性	        
	        $this->assign('properties',          $properties['pro']);                              // 商品属性
	        
	        $this->assign('specification',       $properties['spe']);                              // 商品规格	        
	        $this->assign('fittings',            get_goods_fittings(array($goods_id)));            // 配件
	        $this->assign('rank_prices',         get_user_rank_prices($goods_id, $shop_price));    // 会员等级价格	        
	        $this->assign('pictures',            get_goods_gallery($goods_id,"pc_chanpin"));                    // 商品相册	        
	        $this->assign('goods',               $goods);
	        $this->assign('goods_id',            $goods['goods_id']);
	    }
		/* 记录浏览历史 */
		if (!empty($_COOKIE['ECS']['history'])){
		    $history 						= 	explode(',', $_COOKIE['ECS']['history']);
		
		    array_unshift($history, $goods_id);
		    $history 						= 	array_unique($history);
		
		    while (count($history) > $GLOBALS['_CFG']['history_number']){
		        array_pop($history);
		    }
		
		    setcookie('ECS[history]', implode(',', $history), gmtime() + 3600 * 24 * 30);
		}
		else{
		    setcookie('ECS[history]', $goods_id, gmtime() + 3600 * 24 * 30);
		}
		
		/* 更新点击次数 */
		M()->query('UPDATE ' .'ybr_goods' . " SET click_count = click_count + 1 WHERE goods_id = '$_REQUEST[id]'");		
		$this->display();
   	}

   	/**
   	 * 添加到购物车
   	 * @return
   	 * 		data	0:出错,1,2:出错并跳转,3,4,5,
   	 */
   	public function add_to_cart(){
		
   		$goods				=	$_REQUEST['goods'];
   		
   		/*非法操作*/
	    if (!empty($goods['goods_id']) && empty($goods)){
	        if (!is_numeric($goods['goods_id']) || intval($goods['goods_id']) <= 0){
	            //ecs_header("Location:./\n");
	            $this->ajaxReturn(2,U('goods/index'),1);
	        }
	        $goods_id 		= 	intval($goods['goods_id']);
	    }	    
	    /*商品不存在*/
	    if (empty($_POST['goods'])){
	    	$result['error'] = 1;
			$this->ajaxReturn(1,$result,1);
	    }
		
	    /* 检查：如果商品有规格，而post的数据没有规格，把商品的规格属性通过JSON传到前台 */
	    if (empty($goods['spec']) && empty($goods['quick'])){
	        $sql 	= 	"SELECT a.attr_id, a.attr_name, a.attr_type, ".
	            		"g.goods_attr_id, g.attr_value, g.attr_price " .
				        'FROM ' . 'ybr_goods_attr' . ' AS g ' .
				        'LEFT JOIN ' . 'ybr_attribute' . ' AS a ON a.attr_id = g.attr_id ' .
				        "WHERE a.attr_type != 0 AND g.goods_id = '" . $goods['goods_id'] . "' " .
				        'ORDER BY a.sort_order, g.attr_price, g.goods_attr_id';
	
	        $res 	= 	M()->query($sql);
				        
	        if (!empty($res)){
	            $spe_arr = array();
	            foreach ($res AS $row){
	                $spe_arr[$row['attr_id']]['attr_type'] 	= 	$row['attr_type'];
	                $spe_arr[$row['attr_id']]['name']     	= 	$row['attr_name'];
	                $spe_arr[$row['attr_id']]['attr_id']    = 	$row['attr_id'];
	                $spe_arr[$row['attr_id']]['values'][] 	= 	array(
		                                                            'label'        => $row['attr_value'],
		                                                            'price'        => $row['attr_price'],
		                                                            'format_price' => price_format($row['attr_price'], false),
		                                                            'id'           => $row['goods_attr_id']
	               												);
	          	}
	            $i 			= 	0;
	            $spe_array 	=	array();
	            foreach ($spe_arr AS $row){
	                $spe_array[]	=	$row;
	            }
	            $result['error']   	= 	ERR_NEED_SELECT_ATTR;
	            $result['goods_id'] = 	$goods['goods_id'];
	            $result['parent'] 	= 	$goods['parent'];
	            //$result['message'] 	=	$spe_array;				
	            $result['message']	=	"请选择符合您的产品";
	            $this->ajaxReturn(0,$result,1);
	        }
	    }
	
	    /*更新：如果是一步购物，先清空购物车*/
	    if ($GLOBALS['_CFG']['one_step_buy'] == '1'){
	        clear_cart();
	    }
	
	    /*检查：商品数量是否合法*/
	    if (!is_numeric($goods['number']) || intval($goods['number']) <= 0){
	    	$result['error']   = 1;
        	$result['message'] = $GLOBALS['_LANG']['invalid_number'];
	    }
	    else{	
	        /*更新：添加到购物车*/ 
	        if(addto_cart($goods['goods_id'], $goods['number'], $goods['spec'], $goods['parent'])){
	            if ($GLOBALS['_CFG']['cart_confirm'] > 2){
	                $result['message'] 	= 	'';
	            }
	            else{
	                $result['message'] 	= 	$GLOBALS['_CFG']['cart_confirm'] == 1 ? $GLOBALS['_LANG']['addto_cart_success_1'] : $GLOBALS['_LANG']['addto_cart_success_2'];
	            }
	
	            $result['content'] 		= 	insert_cart_info();
	            $result['one_step_buy'] = 	$GLOBALS['_CFG']['one_step_buy'];	   
	            $result['url']			=	U('flow/index');         
	        }
	        else{	   
	        	$result['message'] 		= 	$GLOBALS['err']->get_error_content();
            	$result['error']    	= 	$GLOBALS['err']->get_error_number();     	
	            $result['goods_id'] 	= 	stripslashes($goods['goods_id']);
	            if (is_array($goods['spec'])){
	                $result['product_spec'] = implode(',', $goods['spec']);
	            }
	            else{
	                $result['product_spec'] = $goods['spec'];
	            }
	        }
	    }	
	    
	    $result['confirm_type'] = !empty($GLOBALS['_CFG']['cart_confirm']) ? $GLOBALS['_CFG']['cart_confirm'] : 2;
	    $this->ajaxReturn(1,$result,1);
   	}
   	
//    /**
//     * 添加到购物车
//     * Enter description here ...
//     */
//    public function add_to_cart(){
//    	
//    	t($_REQUEST);
//    	
//    	
//    	$CommonModel			=	new CommonModel();
//    	$goods					=	$_POST['goods'];
//    	$goods_id				=	intval($goods['goods_id']);		
//    	$goods_number			=	intval($goods['number']);	
//    	if(empty($goods_id)){
//    		$this->error('该商品不存在,请继续购物');
//    	}
//   		/* 检查：商品数量是否合法 */
//	    if (!is_numeric($goods['number']) || intval($goods['number']) <= 0){
//	    	$goods_number		=	1;
//	    }
//    	
//    	// 第一步:处理主商品
//	    /* 更新：如果是一步购物，先清空购物车 */
//	    if ($GLOBALS['_CFG']['one_step_buy'] == '1'){
//	        clear_cart();
//	    }
//	    // 记录住商品信息
//	    $goods['goods_id']			=	$goods_id;
//	    $goods['number']			=	$goods_number; // 默认主商品的信息
//	    
//   		// 更新：添加到购物车
//        if (addto_cart($goods['goods_id'], $goods['number'], $goods['spec'], $goods['parent'])){
//            if ($GLOBALS['_CFG']['cart_confirm'] > 2){
//                $result['message'] 	= 	'';
//            }
//            else{
//                $result['message'] 	= 	$GLOBALS['_CFG']['cart_confirm'] == 1 ? $GLOBALS['_LANG']['addto_cart_success_1'] : $GLOBALS['_LANG']['addto_cart_success_2'];
//            }
//
//            $result['content'] 		= 	insert_cart_info();
//            $result['one_step_buy'] = 	$GLOBALS['_CFG']['one_step_buy'];
//        }
//        else{
//            $result['goods_id'] 	= 	stripslashes($goods['goods_id']);
//            if (is_array($goods['spec'])){
//                $result['product_spec'] 	= 	implode(',', $goods['spec']);
//            }
//            else{
//                $result['product_spec'] 	= 	$goods['spec'];
//            }
//        }
//    
//        // 处理配件
//        $fitting_goods_ids					=	$_POST['fitting_goods_id'];
//        $fitting_goods_number				=	$_POST['goods_number'];
//        $fitting_goods_parent_id			=	$_POST['parent_id'];
//        if(!empty($fitting_goods_ids)){
//        	foreach($fitting_goods_ids as $k => $goods_id){
//	        	$fgoods['goods']			=	$goods_id;	
//	        	$fgoods['number']			=	$fitting_goods_number[$k];	
//	        	$fgoods['parent_id']		=	$fitting_goods_parent_id[$k];
//	        	// 添加配件
//	        	addto_cart($fgoods['goods'],$fgoods['number'],$fgoods['spec'],$fgoods['parent_id']);
//	        }		    	
//        }
//        $this->redirect('/flow/');
//    }
    
    /**
     * 当数量,或属性改变时,相应改变价格
     * Enter description here ...
     */
    public function change_price(){
	    $res    	= 	array('err_msg' => '', 'result' => '', 'qty' => 1);
	
	    $goods_id 	= 	isset($_REQUEST['id'])  ? intval($_REQUEST['id']) : 0;
	    $attr_id    = 	isset($_REQUEST['attr']) ? explode(',', $_REQUEST['attr']) : array();
	    $number     = 	(isset($_REQUEST['number'])) ? intval($_REQUEST['number']) : 1;
	
	    if ($goods_id == 0){
	        $res['err_msg'] 	= 	$GLOBALS['_CFG']['err_change_attr'];
	        $res['err_no']  	= 	1;
	    }
	    else{
	        if ($number == 0){
	            $res['qty'] 	= 	$number = 1;
	        }
	        else{
	            $res['qty'] 	= 	$number;
	        }
	
	        $shop_price  		= 	get_final_price($goods_id, $number, true, $attr_id);
	        
	        $res['result'] 		= 	price_format($shop_price * $number);
	    }	
	    $this->ajaxReturn(1,$res,1);
    }
    
    /**
     * wifi音箱详细介绍页面
     * Enter description here ...
     */
    public function yinxiang(){  
    	$this->assign("menu_selected",			"jiatingbao");  //显示高亮菜单
    	$this->display();
    }
    
    /**
     * 检查库存
     * Enter description here ...
     */
    public function check_stock(){    	
    	$CommonModel	=	new CommonModel();
    	// 获取参数
    	$goods_id		=	intval( $_POST['productid'] );        	
    	$row			=	$CommonModel->getCol("select goods_number from ybr_goods where goods_id = '{$goods_id}'");	
    	if(empty($row)){
    		$this->ajaxReturn(0,0,0);	
    	}
    	else{
    		$this->ajaxReturn(1,$row[0],1);
    	}
    }
    
    /**
     * 礼包+配件
     * Enter description here ...
     */
    public function productpackage(){   
    	 	    	
    	$goods_id			=	intval($_REQUEST['id']);
    	if(empty($goods_id)){
    		$this->error("该商品不存在");
    	}
    	
    	/* 获得商品的信息 */
	    $goods 						= 	get_goods_info($goods_id);
	    $goods['can_buy_number']	=	1;
    	
    	$this->assign('goods',            $goods);            // 主商品
    	
    	$fittings			=	get_goods_fittings(array($goods_id));		
    	// 对比套餐
    	$fittings			=	check_to_package($goods_id,$fittings);
    	// 计算套餐的价值
    	$price_list			=	calculate_package_price($goods,$fittings);
    	// $_SESSION记录选择商品的信息
    	//record_package($goods,$fittings);
    	$this->assign('fittings',      			$fittings);            // 配件    	
    	$this->assign('price_list',      $price_list);            // 配件    	
    	$this->display();
    }
    
    //U盘
    public function upan(){
    	
    }
    
    //mini音箱
    public function miniyinxiang(){
    	
    }
    
    //插座
    public function chazuo(){
    	
    }
    
    //无线耳机
    public function wuxianerji(){
    
    }
    
    //音乐盒子
    public function musicbox(){
    	echo "音乐盒子";
    	$this->display();
    }
    
    
}









